package com.summer.learn.handlers;

import com.summer.learn.dao.EmployeeDao;
import com.summer.learn.modle.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Date;
import java.util.Locale;

@Controller
public class SpringMvcTest {

    @Autowired
    private EmployeeDao employeeDao;

    @Autowired
    private ResourceBundleMessageSource messageSource;

    @RequestMapping(value = "testConversionServiceConverter", method = RequestMethod.POST)
    public String testConversionServiceConverter(/*@RequestParam("employee") */Employee employee) {
        System.out.println("testConversionServiceConverter : " + employee);
        employeeDao.save(employee);
        return "redirect:employees";
    }

    @ResponseBody
    @RequestMapping(value = "testJson")
    public Collection<Employee> testJson() {
        return employeeDao.getAll();
    }

    @ResponseBody
    @RequestMapping("testHttpMessageConverter")
    public String testHttpMessageConverter(@RequestBody String body) {
        System.out.println(body);
        return "hello mvc  " + new Date().getTime();
    }

    @RequestMapping("testResponseEntity")
    public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException {
        ServletContext servletContext = session.getServletContext();
        InputStream inputStream = servletContext.getResourceAsStream("/file/test.txt");
        byte[] data = new byte[inputStream.available()];
        inputStream.read(data);

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-Disposition", "attachment;filename=abc.txt");

        HttpStatus statusCode = HttpStatus.OK;

        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(data, httpHeaders, statusCode);
        return responseEntity;
    }

    @RequestMapping("i18n1")
    public String i18n1(Locale locale) {
        String message = messageSource.getMessage("i18n.username", null, locale);
        System.out.println("message:"+message);
        return "i18n1";
    }


    @RequestMapping("testFileUpload")
    public String testFileUpload(@RequestParam("desc") String desc, @RequestParam("file") MultipartFile file) throws IOException {
        System.out.println("desc:"+desc);
        System.out.println("fileName:"+file.getOriginalFilename());
        System.out.println("file input:" + file.getInputStream());
        return "hello";
    }

    /*******************************************异常处理以下**************************************************************/

//    @ExceptionHandler({RuntimeException.class})
//    public ModelAndView handleArithmeticException1(Exception ex) {
//        System.out.println("handleArithmeticException 更高级别:" + ex);
//        ModelAndView mv = new ModelAndView("error");
//        mv.addObject("ex", ex);
//        return mv;
//    }

    /**
     * 1。在 @ExceptionHandler 方法的入参中可以加入 Exception 类型的参数，该参数即对应发生的异常对象
     * 2，@ExceptionHandler 方法的入参中不能传入 Map，若希望把异常信息传导页面上，需要使用 ModelAndView 作为返回值
     * 3.@ExceptionHandler 方法标记的异常有优先级的间题。如果能精准定位到具体类型则匹配具体的类型处理，否则匹配父类类型处理。
     * 4.@ControllerAdvice:如果在当前Handler中找不到@ExceptionHandler方法来出来当前方法出现的异常，
     * 则将去 @ControllerAdvice 标记的类中查找 @ExceptionHandler 标记的方法来处理异常。
     */
    @ExceptionHandler({ArithmeticException.class})
    public ModelAndView handleArithmeticException(Exception ex) {
        System.out.println("handleArithmeticException:" + ex);
        ModelAndView mv = new ModelAndView("error");
        mv.addObject("ex", ex);
        return mv;
    }

    @RequestMapping("testExceptionHandlerExceptionResolver")
    public String testExceptionHandlerExceptionResolver(int i) {
        System.out.println("testExceptionHandlerExceptionResolver:" + (10 / i));
        return "hello";
    }

    @ResponseStatus(value = HttpStatus.FORBIDDEN, reason = "这个注解写在方法上，不管有没有异常都会返回异常页")
    @RequestMapping("testResponseStatusExceptionResolver")
    public String testResponseStatusExceptionResolver(int i) {
        if(i==13) {
            throw new UserNameNotMatchPasswordException();
        }
        System.out.println("testResponseStatusExceptionResolver.....");
        return "hello";
    }

    @RequestMapping(value = "testHandlerExceptionResolver", method = RequestMethod.POST)
    public String testHandlerExceptionResolver() {
        System.out.println("testHandlerExceptionResolver.....");
        return "hello";
    }

    @RequestMapping(value = "testSimpleMappingExceptionResolver")
    public String testSimpleMappingExceptionResolver(@RequestParam("i") int i) {
        String[] arry = new String[10];
        System.out.println("testSimpleMappingExceptionResolver:" + arry[i]);
        return "hello";
    }
}
